package com.bss.utils;

import java.util.List;
import java.util.TimeZone;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import com.bss.dao.UserDao;
import com.bss.model.User;

@Component
@Scope("session")
public class Preferences {

	private static final String DEFAULT_SKIN = "classic";

	private String skin = null;

	@Autowired
	private UserDao userDao;

	private TimeZone timeZone = TimeZone.getTimeZone("IST");

	private User user;

	public void setSkin(String skin) {
		this.skin = skin;
		if (this.user != null) {
			List<User> users = this.userDao.find("username='" + this.user.getUsername() + "'");

			User user = users.get(0);

			user.setSkin(skin);
			this.userDao.update(user);

		}

	}

	public String getSkin() {

		if (this.skin == null) {

			Authentication auth = SecurityContextHolder.getContext().getAuthentication();
			if ((auth == null) || (auth.getPrincipal() instanceof String)) {
				return Preferences.DEFAULT_SKIN;
			}

			String name = auth.getName();

			List<User> users = this.userDao.find("username='" + name + "'");

			if ((users == null) || (users.size() == 0)) {
				this.skin = Preferences.DEFAULT_SKIN;
			} else {
				User user = users.get(0);
				this.user = user;
				if (user.getSkin() == null) {
					this.skin = Preferences.DEFAULT_SKIN;
				} else {
					this.skin = user.getSkin();
				}
			}
		}
		return this.skin;
	}

	public void setTimeZone(TimeZone timeZone) {
		this.timeZone = timeZone;
	}

	public TimeZone getTimeZone() {
		return this.timeZone;
	}

}
